package com.alibaba.nacos;

import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class TomcatApplication {

    public static void main(String[] args) throws Exception {
        // 创建 Tomcat 实例
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8080); // 设置 Tomcat 监听的端口
        tomcat.getConnector();

        // 通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(NacosConfig.class);
        context.refresh();

        // 创建并配置 Spring MVC 的 DispatcherServlet
        Context tomcatContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));   //基于java代码的方式初始化DispatcherServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
        Tomcat.addServlet(tomcatContext, "dispatcher", dispatcherServlet);//绑定servlet
        tomcatContext.addServletMappingDecoded("/", "dispatcher");

        // 启动 Tomcat
        tomcat.start();
        System.out.println("Tomcat started on http://localhost:8080");
        //tomcat启动后，让其阻塞，不让当前线程结束，等待处理请求
        tomcat.getServer().await();
    }
}
